package com.cloud.project.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cloud.platform.Constants;
import com.cloud.platform.IDao;
import com.cloud.platform.StringUtil;
import com.cloud.project.model.Project;

@Service
public class ProjectService {

	@Autowired
	private IDao dao;
	
	/**
	 * get bug by id
	 * 
	 * @param bugId
	 * @return
	 */
	public Project getProject(String projectId) {
		
		if(StringUtil.isNullOrEmpty(projectId)) {
			return new Project();
		}
		
		Project project = (Project) dao.getObject(Project.class, projectId);
		
		return project;
	}
	
	/**
	 * search type users
	 * 
	 * @param type
	 * @return
	 */
	public List<Project> searchProjects(String managerId) {
		
		// search projects
		String hql = "select p,u.username from Project p,User u where p.managerId = u.id";
		
		if(!StringUtil.isNullOrEmpty(managerId)) {
			hql += " and p.managerId='" + managerId + "'";
		}
		
		hql += " order by p.createTime desc";
		
		List<Object[]> list = dao.getAllByHql(hql);
		
		// combine manager name
		Project p = null;
		List<Project> projects = new ArrayList();
		
		for(Object[] o : list) {
			p = (Project) o[0];
			p.setManager((String) o[1]);
			
			projects.add(p);
		}
		
		return projects;
	}
	
	/**
	 * save project
	 * 
	 * @param project
	 */
	public void saveProject(Project project) {
		
		project.setId(Constants.getID());
		project.setCreateTime(new Date());
		
		project.setIntro(project.getIntro().replaceAll("\r\n", "<br>"));
		
		dao.saveObject(project);
		
		// reset project map
		Constants.projectNameIdMap = null;
	}
}
